#!/usr/bin/env python
#gstart.py

"""G-Start reads from list of applications and executes them  with time offset.

"""

import time
import subprocess
import shlex
import pygtk
pygtk.require("2.0")
import gtk
import gobject

import config
from gui.mainwindow import MainWindow
from gui.trayicon import TrayIcon

_ticks = -1

def main():
    #read values from config file
    time_list = config.read_times()
    
    global mainWindow
    global trayIcon
    
    mainWindow = MainWindow(time_list)
    mainWindow.set_on_destroy_handler(mainwindow_destroy)
    mainWindow.set_on_execute_handler(mainwindow_execute)
    #mainWindow.show()
    
    trayIcon = TrayIcon(mainWindow)
    trayIcon.show()
    
    gobject.timeout_add(1000, second_tick, time_list)
    gtk.gdk.threads_init()
    gtk.main()
       
def second_tick(time_list):
    global mainWindow
    if mainWindow.is_destroyed():
        return False
    
    global _ticks
    _ticks += 1
    print _ticks
    
    tdef = time_list.tick()
    mainWindow.update_timer(tdef)
    
    if tdef.time_left() <= 0:
        execute(tdef)        
    if time_list.count() > 0:
        return True
    else:        
        mainWindow.destroy()
        return False

def mainwindow_execute(tdef):
    execute(tdef)
    
def mainwindow_destroy():
    gtk.main_quit()

def execute(tdef):
    if not tdef.active():
	return

    global mainWindow
    tdef.done()
    mainWindow.set_executed(tdef.name())
    print str(_ticks) + " Executing: " + tdef.name() +": " + tdef.path()
    subprocess.Popen(shlex.split(tdef.path()),
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE, 
            stdin=subprocess.PIPE)

if __name__ == "__main__":
    main()
